package com.example.bijidemo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.bijidemo.common.R;
import com.example.bijidemo.dto.LogDto;
import com.example.bijidemo.entity.Log;
import com.example.bijidemo.entity.xxx;
import com.example.bijidemo.service.LogService;
import com.example.bijidemo.service.XxxService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/log")
@Slf4j
public class LogController {
    @Autowired
    XxxService xxxService;
    @Autowired
    LogService logService;
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String userName){
        //创建两个分页
        Page<xxx> xxxPage=new Page<>();
        Page<LogDto> dtoPage=new Page<>();
        //根据创建时间进行一个xxx表的排序
        LambdaQueryWrapper<xxx> a=new LambdaQueryWrapper<>();
        a.orderByDesc(xxx::getCreateDate);
        xxxService.page(xxxPage,a);
        BeanUtils.copyProperties(xxxPage,dtoPage,"records");
      List<LogDto> logDtoList=  xxxPage.getRecords().stream().map((item)->{
            LogDto logDto=new LogDto();
            BeanUtils.copyProperties(item,logDto);
            LambdaQueryWrapper<Log> log=new LambdaQueryWrapper<>();
            log.eq(Log::getXxxId,item.getId());
            List<Log> list = logService.list(log);
            if (list!=null){
                logDto.setOperations(list);
            }

            return logDto;

        }).collect(Collectors.toList());
      if (userName!=null){
         List<LogDto> logDtoList1= logDtoList.stream().filter(s->s.getUsername().contains(userName)).collect(Collectors.toList());
          dtoPage.setRecords(logDtoList1);
          return R.success(dtoPage);

      }
      dtoPage.setRecords(logDtoList);
      return R.success(dtoPage);

    }

    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable Long id){
        xxxService.removeById(id);
        LambdaQueryWrapper<Log> a=new LambdaQueryWrapper<>();
        a.eq(Log::getXxxId,id);
        logService.remove(a);
        return  R.success("删除成功");

    }
}
